package com.cljz.makepassenger.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Selection;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.cljz.makepassenger.base.App;
import com.cljz.makepassenger.R;
import com.cljz.makepassenger.base.BaseActivity;
import com.cljz.makepassenger.model.net.bean.GetCityBean;
import com.cljz.makepassenger.model.map.City;
import com.cljz.makepassenger.present.activity.SearchSiteP;
import com.cljz.makepassenger.ui.adapter.SearchSiteAdapter;
import com.cljz.makepassenger.utils.L;
import com.cljz.makepassenger.widget.ClearEditText;
import com.jakewharton.rxbinding.view.RxView;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.droidlover.xdroidmvp.router.Router;
import rx.functions.Action1;

/**
 * Created by apple on 2017/4/8.
 */

public class SearchSiteActivity extends BaseActivity<SearchSiteP> implements OnGetPoiSearchResultListener {
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.cet_search)
    ClearEditText cetSearch;
    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.activity_map_toolbar)
    RelativeLayout activityMapToolbar;
    @BindView(R.id.cv_title)
    CardView cvTitle;
    @BindView(R.id.tv_search_result)
    TextView tvSearchResult;
    @BindView(R.id.rv_search_site)
    XRecyclerView rvSearchSite;
    @BindView(R.id.ll_search_result)
    LinearLayout llSearchResult;

    private int page = 1;
    private boolean isLoadMore;
    private SearchSiteAdapter searchSiteAdapter;
    private PoiSearch mPoiSearch;
    private List<PoiInfo> siteList = new ArrayList<>();
    private City city = null;

    @Override
    public void initData(Bundle savedInstanceState) {
        tvCity.setText(getIntent().getExtras().getString("city"));
        initRecycleView();
        initBaidu();
    }

    private void initBaidu() {
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);
    }

    private void initRecycleView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvSearchSite.setLayoutManager(layoutManager);
        searchSiteAdapter = new SearchSiteAdapter(App.getInstance(), siteList);
        rvSearchSite.setAdapter(searchSiteAdapter);
        rvSearchSite.setLoadingMoreEnabled(true);
        rvSearchSite.setPullRefreshEnabled(false);
        rvSearchSite.setLoadingMoreProgressStyle(ProgressStyle.BallClipRotate);
    }

    @Override
    protected void initListener() {
        super.initListener();
        RxView.clicks(tvCancel)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                finish();
            }
        });
        RxView.clicks(tvCity)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                Router.newIntent((Activity) App.getInstance()).putString("city", tvCity.getText().toString().trim()).requestCode(12).to(CityListActivity.class).launch();
            }
        });
        RxTextView.textChanges(cetSearch)
                .compose(this.<CharSequence>bindToLifecycle())
                .subscribe(new Action1<CharSequence>() {
            @Override
            public void call(CharSequence charSequence) {
                rvSearchSite.setLoadingMoreEnabled(true);
                siteList.clear();
                searchSiteAdapter.setSiteList(siteList);
                Selection.setSelection(cetSearch.getText(), charSequence.length());
                mPoiSearch.searchInCity((new PoiCitySearchOption())
                        .city(tvCity.getText().toString().trim())
                        .keyword(charSequence.toString())
                        .pageNum(page));
            }
        });
        rvSearchSite.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
            }
            @Override
            public void onLoadMore() {
                page++;
                isLoadMore = true;
                mPoiSearch.searchInCity((new PoiCitySearchOption())
                        .city(tvCity.getText().toString().trim())
                        .keyword(cetSearch.getText().toString().trim())
                        .pageNum(page));
            }
        });
        searchSiteAdapter.setOnItemClickListener(new SearchSiteAdapter.OnItemClickListener() {
            @Override
            public void onClick(PoiInfo poiInfo) {
                if (city == null)
                    city = new City();
                city.setLongitude(poiInfo.location.longitude);
                city.setLatitude(poiInfo.location.latitude);
                city.setAreaName(poiInfo.name);
                city.setAddress(poiInfo.address);
                city.setCityName(poiInfo.city);
                L.e("city:" + city.toString());
                Intent intent = new Intent();
                intent.putExtra("data", city);
                setResult(RESULT_OK, intent);
                hideSoftKeyboard();
                finish();
            }
            @Override
            public void onLongClick(PoiInfo poiInfo) {
            }
        });
    }

    /*private void setData2List() {
        int adapterSize = page *10;
        if (poiResultList.size() > 0) {
            if (poiResultList.size() >= adapterSize) {
                if (isLoadMore) {
                    for (int i = 0; i < adapterSize; i++) {
                        if (i > adapterSize - 11) {
                            siteList.add(poiResultList.get(i));
                        }
                    }
                    searchSiteAdapter.addSiteList(siteList);
                    rvSearchSite.loadMoreComplete();
                }else {
                    for (int i = 0; i < adapterSize; i++) {
                        siteList.add(poiResultList.get(i));
                    }
                    searchSiteAdapter.setSiteList(siteList);
                }
            } else {
                if (isLoadMore) {
                    for (int i = 0; i < adapterSize; i++) {
                        if (i > adapterSize - 11) {
                            siteList.add(poiResultList.get(i));
                        }
                    }
                    searchSiteAdapter.addSiteList(siteList);
                    rvSearchSite.loadMoreComplete();
                }else {
                    for (int i = 0; i < adapterSize; i++) {
                        siteList.add(poiResultList.get(i));
                    }
                    searchSiteAdapter.setSiteList(siteList);
                }
            }
        }else {
            showSnackBar(cvTitle,"没有更多了...");
        }
        isLoadMore = false;
    }*/

    @Override
    public int getLayoutId() {
        return R.layout.activity_search_site;
    }

    @Override
    public SearchSiteP newP() {
        return new SearchSiteP();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 12 && resultCode == RESULT_OK) {
            city = (City) data.getSerializableExtra("data");
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    tvCity.setText(city.getAreaName());
                    getP().getCity(city.getProvice(), city.getAreaName());
                }
            };
            runOnUiThread(runnable);
        }
    }

    @Override
    protected void setScreen() {
        super.setScreen();
        SDKInitializer.initialize(getApplicationContext());

    }

    @Override
    public void onGetPoiResult(PoiResult poiResult) {
        if (poiResult != null && poiResult.getAllPoi() != null) {
            if (isLoadMore) {
                siteList.addAll(poiResult.getAllPoi());
                searchSiteAdapter.addSiteList(siteList);
                isLoadMore = false;
                rvSearchSite.loadMoreComplete();
            } else {
                siteList.clear();
                siteList.addAll(poiResult.getAllPoi());
                searchSiteAdapter.setSiteList(siteList);
                page = 1;
            }

        }else {
            rvSearchSite.setLoadingMoreEnabled(false);
        }
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }

    public void getCityFail(String error) {
    }

    public void getCitySucceed(GetCityBean getCityBean) {
        city.setCity_id(getCityBean.getData().getCity_id());
    }
}
